<?php
/*
 * @Author: CHINAKAIYUAN<sunkaiyuan@namenode.cn>
 * @Date: 2022-02-03 00:33:05
 * @LastEditTime: 2023-01-09 16:25:36
 * @LastEditors: sunkaiyuan sunkaiyuan@namenode.com
 * @Description: 
 */

namespace App\Models;

use App\Repositories\FinanceVoucherRepository;
use App\Traits\SoftDeletesTrait;
use App\Traits\AttachmentTrait;
use App\Traits\AutoCodeTrait;
use App\Traits\VoucherTrait;

class PurchaseOrder extends BaseModel
    {
    use SoftDeletesTrait;
    use AutoCodeTrait;
    use AttachmentTrait;
    use VoucherTrait;
    public $timestamps = true;
    public $table = "sys_purchase_order";
    protected $guarded = [];
    //附件
    public $attachmentkey = "code";
    protected $casts = [
        'tax'        => 'decimal:2',
        'amount'     => 'decimal:2',
        'tax_amount' => 'decimal:2',
        'rate'       => 'decimal:2',
    ];

    /**
     * 标识
     *
     * @var string
     */
    protected $ACSign = 'PURCHASE_ORDER';

    /**
     * 编号所用的字段
     *
     * @var string
     */
    protected $ACCode = 'code';

    public function status()
        {
        return $this->belongsTo(Dic::class, "status_id", "key")->where(function ($q)
            {
            $q->where("code", 'status_with_finance');
            });
        }
    public function company()
        {
        return $this->belongsTo(Company::class);
        }
    public function extra_cost_details()
        {
        return $this->hasMany(MarketDeliveryExtraCost::class, "code", "code");
        }
    public function details()
        {
        return $this->hasMany(PurchaseOrderDetails::class, "main_id");
        }
    public function tax()
        {
        return $this->belongsTo(Dic::class, "tax_id", "key")->where(function ($q)
            {
            $q->where("code", 'FinanceTax');
            });
        }


    public function finance($order = null)
        {
        $v = $order ?? $this;

        if ($v->status_id == 2)
            return $v->voucher;

        if ($v->status_id != 1) {
            fail("单据非审核状态！，无法财审！");
            }

        $details       = [];
        $debit_subject = $credit_subject = null;
        //样品到货不做凭证
        $need_voucher = $v->type == 1 ? false : true;
        //摘要
        $summary = $v->finance_remark;
        //采购入库，采购退货
        //借库存商品1405 
        $debit_subject = 1405;
        //贷应付账款 2202 
        $credit_subject = 2202;
        $summary        = "采购";
        $sum_quantity   = $v->details->sum("quantity");
        $sum_ex_amount  = $v->extra_cost_details->sum("amount");
        $new_ex_amount  = 0;
        //借方分录  
        $v->details->map(function ($v) use ($debit_subject, &$details, $credit_subject, $summary, $need_voucher, $sum_quantity, $sum_ex_amount, &$new_ex_amount)
            {
            fauditSave($v);
            if ($need_voucher) {
                $merge_Data             = $v->toArray();
                $merge_Data['quantity'] = $v->quantity;
                $merge_Data['price']    = $v->price;
                $ex_amount              = $v->quantity / $sum_quantity * $sum_ex_amount;//分摊额外金额
                $new_ex_amount += $ex_amount;
                // 22210101
                if ($v->tax_id == 1) {
                    $notax_amount = $v['amount'] / (1 + $v->material->tax_rate / 100);
                    $tax_amount   = $v['amount'] - $notax_amount;
                    $details[]    = FinanceVoucherRepository::mergeVoucher(22210101, $summary, $tax_amount, 0);
                    }
                else {
                    $notax_amount = $v['amount'];
                    }
                $details[] = FinanceVoucherRepository::mergeVoucher($debit_subject, $summary, $notax_amount, 0, $merge_Data);
                $details[] = FinanceVoucherRepository::mergeVoucher($credit_subject, $summary, 0, $v['amount'], $merge_Data, 0, $v->tax_id);
                $details[] = FinanceVoucherRepository::mergeVoucher($debit_subject, "额外费用分摊", $ex_amount, 0, $merge_Data, 0, $v->tax_id);
                }
            })->toArray();
        //审核 
        $ex_remark = $v->extra_cost_details
            ->map(function ($v)
                {
                return "[{$v->extra_cost}]{$v->remark}";
                })
            ->implode(";");
        if ($new_ex_amount > 0)
            $details[] = FinanceVoucherRepository::mergeVoucher($credit_subject, $ex_remark, 0, $new_ex_amount, array_merge($v->toArray(), [
                'quantity'    => 0,
                'mi_quantity' => 0,
                'price'       => 0,
                'company_id'  => $v->company_id
            ]), 0, $v->tax_id);

        fauditSave($v);
        $voucher = null;
        if ($need_voucher) {
            //贷方分录  
            $voucher = FinanceVoucherRepository::CreateVoucher($v->billdate ?? $v->updated_at, 1, $details, $v, $v->voucher?->id);
            //创建凭证
            $voucher = FinanceVoucherRepository::auditVoucher($voucher);
            }
        //返回凭证
        return $voucher;
        }
    public function nofinance($order = null)
        {
        $v = $order ?? $this;
        if ($v->status_id == 1)
            return $v->voucher;
        if ($v->status_id != 2) {
            fail("非财审状态！，无法取消财审！");
            }
        if (($v->voucher?->status_id ?? 0) != 0) {
            fail("凭证【{$v->voucher->code}】已记账！ 操作失败！");
            }
        $v->details->filter(function ($v)
            {
            fauditSave($v, false);
            });

        return fauditSave($v, false);

        }

    }